#!/bin/bash
# 作用检测mysql，redis都启动了， 再启动java程序
FILE_COUNT=$#
if((FILE_COUNT==0)); then
    echo "错误：未传递文件参数端口！"
    echo "用法：startup.sh cmd 依赖端口1 端口2"
    echo "举例：startup.sh /root/xx.sh 3306 6379"
    exit;
fi

# exit 0;
#================== 环境变量 ====================
log_path="/root/startup.log"
data_format=`date "+%Y-%m-%d %H:%M:%S"`
rm -f $log_path

#================== 检测函数 ====================
function startup_check_port () {
port=$1
port_count=0
while [ $port_count = 0 ]; do
    # body
    echo $data_format"   [未检测到$port]"
    echo $data_format"   [未检测到$port]" >> $log_path
    sleep 2
    port_count=`netstat -nltp | grep $port | wc -l`
done
echo $data_format"   [$port已经启动]"
echo $data_format"   [$port已经启动]"  >> $log_path
}

#================== 自定义调用 ====================
# 启动检测
# startup_check_port 6379
# startup_check_port 3306
# 启动用户自定义程序

for arg in $*; do
    case "$arg" in
    [1-9][0-9]*)
     startup_check_port $arg;;
    esac
done
# 执行
cmd=$1
echo $data_format"   [依赖服务都已经启动，准备启动用户程序 $cmd]"
echo $data_format"   [依赖服务都已经启动，准备启动用户程序 $cmd]" >> $log_path

# 调用执行
$cmd
#===================系统重启后=====================
# [root@mini ~]# ll /etc/rc.d//rc.local
# -rwxr-xr-x 1 root root 556 3月   5 09:49 /etc/rc.d//rc.local
# [root@mini ~]# cat /etc/rc.d/rc.local
# #!/bin/bash
# sh /root/startup.sh "echo abc" 6379 6380
# 或者
# nohup sh /root/startup.sh "echo abc" 6379 6380 &
# [root@mini ~]#

#===================系统重启后=====================

# -rw-r--r--   1 root root      1025 3月   5 09:51 startup.log
# -rwxr-xr-x   1 root root      1376 3月   5 09:48 startup.sh
# [root@mini ~]# tail -f startup.log
# 2023-03-05 09:51:09   [未检测到6379]
# 2023-03-05 09:51:09   [未检测到6379]
# 2023-03-05 09:51:09   [未检测到6379]
# 2023-03-05 09:51:09   [6379已经启动]
# 2023-03-05 09:51:09   [未检测到6380]
# 2023-03-05 09:51:09   [未检测到6380]
# 2023-03-05 09:51:09   [6380已经启动]
# 2023-03-05 09:51:09   [依赖服务都已经启动，准备启动用户程序 echo abc]